##参考RSI模式计算上一分钟的ma5，ma10，ma20
##输入股票代码,返回当前的时间的上一分钟的ma5，ma10，ma20
from xtquant import xtdata
from typing import Dict, Optional, Union, Tuple
import pandas as pd
from datetime import datetime
import time


class IndependentMACalculator:
    """
    完全独立的MA计算器

    特性：
    1. 不依赖订阅，直接使用xtdata获取历史数据
    2. 输入股票代码即可获取最新MA5、MA10、MA20（上一分钟结束时的MA）
    3. 自动下载当日分钟数据并计算
    4. 支持缓存，避免重复下载

    使用方法：
        ma_calc = IndependentMACalculator(xtdata=xtdata)
        ma5, ma10, ma20 = ma_calc.get_latest_ma("513050.SH")  # 直接获取最新MA
    """

    def __init__(self, xtdata=None):
        self.xtdata = xtdata
        
        # MA周期设置
        self.ma_periods = [5, 10, 20, 30]
        
        # 每个股票的状态 - 存储最近的价格数据
        self._price_history: Dict[str, list] = {}
        
        # 缓存机制：避免重复下载同一天的数据
        self._cache_date: Dict[str, str] = {}  # 股票代码 -> 缓存日期
        self._cache_ttl: int = 60  # 缓存有效期（秒）- 1分钟更新一次确保获取最新完整分钟数据
        self._cache_time: Dict[str, float] = {}  # 股票代码 -> 缓存时间戳
        self._cache_minute: Dict[str, str] = {}  # 股票代码 -> 缓存的分钟时间戳

        # 交易时间段常量
        self.MORNING_START = datetime.strptime("09:30", "%H:%M").time()
        self.MORNING_END = datetime.strptime("11:30", "%H:%M").time()
        self.AFTERNOON_START = datetime.strptime("13:00", "%H:%M").time()
        self.AFTERNOON_END = datetime.strptime("15:00", "%H:%M").time()

    def reset(self, stock_code: Optional[str] = None) -> None:
        """重置指定股票或全部股票的MA状态"""
        if stock_code is None:
            self._price_history.clear()
            self._cache_date.clear()
            self._cache_time.clear()
            self._cache_minute.clear()
            return

        self._price_history.pop(stock_code, None)
        self._cache_date.pop(stock_code, None)
        self._cache_time.pop(stock_code, None)
        self._cache_minute.pop(stock_code, None)

    def _is_cache_valid(self, stock_code: str, today: str) -> bool:
        """检查缓存是否有效"""
        if stock_code not in self._cache_date or stock_code not in self._cache_time:
            return False

        # 检查日期是否匹配
        if self._cache_date[stock_code] != today:
            return False

        # 检查当前分钟是否与缓存分钟相同
        current_minute = datetime.now().strftime("%Y%m%d%H%M")
        cached_minute = self._cache_minute.get(stock_code, "")
        if cached_minute != current_minute:
            return False

        # 检查时间是否在有效期内
        current_time = time.time()
        cache_time = self._cache_time[stock_code]
        return (current_time - cache_time) < self._cache_ttl

    def _download_minute_data(self, stock_code: str, date: str) -> bool:
        """下载指定股票的当日分钟数据"""
        if not self.xtdata:
            print("⚠️ xtdata未初始化，无法下载数据")
            return False

        try:
            self.xtdata.download_history_data(
                stock_code=stock_code,
                period="1m",
                start_time=date,
                end_time=date
            )
            time.sleep(0.1)  # 避免请求过快
            return True
        except Exception as e:
            print(f"⚠️ {stock_code} 分钟数据下载失败: {e}")
            return False

    def _get_minute_data(self, stock_code: str, date: str) -> Optional[pd.DataFrame]:
        """获取指定股票的当日分钟数据"""
        if not self.xtdata:
            return None

        try:
            data = self.xtdata.get_local_data(
                stock_list=[stock_code],
                period='1m',
                start_time=date,
                end_time=date
            )

            df = data.get(stock_code) if data else None
            if df is None or df.empty:
                return None

            # 识别时间列和价格列
            time_col = next((c for c in df.columns if 'time' in c.lower()), None)
            # 价格列优先级：优先使用close，然后是lastPrice，最后是其他
            price_cols = ['close', 'lastPrice', 'price', 'last', 'current']
            price_col = next((c for c in price_cols if c in df.columns), None)

            # 调试信息：显示列名
            print(f"🔍 {stock_code} 数据列名: {list(df.columns)}")
            print(f"🔍 {stock_code} 时间列: {time_col}, 价格列: {price_col}")
            
            # 显示所有可能的价格列及其值
            for col in price_cols:
                if col in df.columns:
                    sample_values = df[col].dropna().head(3).tolist()
                    print(f"🔍 {stock_code} {col}列样本值: {sample_values}")

            if not time_col or not price_col:
                print(f"⚠️ {stock_code} 无法识别时间列或价格列")
                return None

            # 时间格式统一处理
            print(f"🔍 {stock_code} 原始时间列类型: {df[time_col].dtype}")
            print(f"🔍 {stock_code} 原始时间样本: {df[time_col].head(3).tolist()}")
            
            if str(df[time_col].dtype) in ('int64', 'float64'):
                df['__time__'] = pd.to_datetime(df[time_col], unit='ms') + pd.Timedelta(hours=8)
                print(f"🔍 {stock_code} 使用毫秒时间戳转换")
            else:
                try:
                    df['__time__'] = pd.to_datetime(df[time_col], format='%Y%m%d%H%M%S', errors='coerce')
                    print(f"🔍 {stock_code} 使用格式化时间转换")
                except Exception:
                    df['__time__'] = pd.to_datetime(df[time_col], errors='coerce')
                    print(f"🔍 {stock_code} 使用自动时间转换")

            df = df[df['__time__'].notna()].sort_values('__time__')
            print(f"🔍 {stock_code} 转换后时间样本: {df['__time__'].head(3).dt.strftime('%Y-%m-%d %H:%M:%S').tolist()}")

            # 添加列名到DataFrame以便后续使用
            df._price_col = price_col

            return df if not df.empty else None

        except Exception as e:
            print(f"⚠️ {stock_code} 分钟数据获取失败: {e}")
            return None

    def _filter_trading_session_data(self, df: pd.DataFrame, end_time: Optional[datetime] = None) -> pd.DataFrame:
        """筛选交易时段内的数据，并排除当前未完成的分钟"""
        try:
            print(f"🔍 交易时段过滤前数据量: {len(df)}")
            
            # 先筛选交易时段内的数据
            mask = [((self.MORNING_START <= ts.time() <= self.MORNING_END) or
                     (self.AFTERNOON_START <= ts.time() <= self.AFTERNOON_END)) for ts in df['__time__']]
            if any(mask):
                filtered_df = df[mask]
                print(f"🔍 交易时段过滤后数据量: {len(filtered_df)}")

                # 确定截止时间
                if end_time is not None:
                    # 回测模式：使用指定的结束时间
                    cutoff_time = end_time.replace(second=0, microsecond=0)
                    print(f"🔍 回测模式截止时间: {cutoff_time.strftime('%H:%M')}")
                else:
                    # 实时模式：使用当前时间
                    current_time = datetime.now()
                    cutoff_time = current_time.replace(second=0, microsecond=0)
                    print(f"🔍 实时模式截止时间: {cutoff_time.strftime('%H:%M')}")

                # 只保留时间小于截止分钟的数据（即已完成的分钟）
                complete_mask = filtered_df['__time__'] < cutoff_time
                if complete_mask.any():
                    final_df = filtered_df[complete_mask]
                    print(f"🔍 最终过滤后数据量: {len(final_df)}")
                    return final_df
                else:
                    print(f"🔍 没有完整分钟数据，返回交易时段数据")
                    return filtered_df  # 如果没有完整分钟数据，返回原数据
            else:
                print(f"🔍 没有交易时段数据")
                return df
        except Exception as e:
            print(f"⚠️ 交易时段过滤异常: {e}")
            pass
        return df

    def _calculate_ma_from_data(self, stock_code: str, df: pd.DataFrame) -> Optional[Tuple[float, float, float]]:
        """从分钟数据计算MA5、MA10、MA20"""
        try:
            # 安全地获取价格列名
            price_col = getattr(df, '_price_col', None)
            if not price_col:
                # 如果没有_price_col属性，重新识别价格列
                price_col = next((c for c in ['close', 'lastPrice', 'price', 'last', 'current'] if c in df.columns),
                                 None)
                if not price_col:
                    print(f"⚠️ {stock_code} 无法识别价格列")
                    return None

            prices = df[price_col].dropna().tolist()
            
            # 调试信息：显示数据范围
            if not df.empty and '__time__' in df.columns:
                start_time = df['__time__'].min()
                end_time = df['__time__'].max()
                print(f"📊 {stock_code} 数据范围: {start_time.strftime('%H:%M')} - {end_time.strftime('%H:%M')}, 共{len(prices)}个数据点")
                
                # 显示最后几个价格和时间点
                if len(prices) >= 5:
                    print(f"📊 {stock_code} 最后5个价格: {[f'{p:.3f}' for p in prices[-5:]]}")
                    last_times = df['__time__'].tail(5).dt.strftime('%H:%M').tolist()
                    print(f"📊 {stock_code} 最后5个时间: {last_times}")

            if len(prices) < max(self.ma_periods):
                print(f"⚠️ {stock_code} 数据不足，需要至少{max(self.ma_periods)}个数据点，实际只有{len(prices)}个")
                return None

            # 计算MA5、MA10、MA20、MA30
            ma5 = sum(prices[-5:]) / 5 if len(prices) >= 5 else None
            ma10 = sum(prices[-10:]) / 10 if len(prices) >= 10 else None
            ma20 = sum(prices[-20:]) / 20 if len(prices) >= 20 else None
            ma30 = sum(prices[-30:]) / 30 if len(prices) >= 30 else None

            # 调试信息：显示MA计算详情
            if ma5 is not None:
                print(f"📈 {stock_code} MA5计算: {[f'{p:.3f}' for p in prices[-5:]]} -> {ma5:.3f}")
            if ma10 is not None:
                print(f"📈 {stock_code} MA10计算: {[f'{p:.3f}' for p in prices[-10:]]} -> {ma10:.3f}")
            if ma20 is not None:
                print(f"📈 {stock_code} MA20计算: {[f'{p:.3f}' for p in prices[-20:]]} -> {ma20:.3f}")
            if ma30 is not None:
                print(f"📈 {stock_code} MA30计算: {[f'{p:.3f}' for p in prices[-30:]]} -> {ma30:.3f}")

            # 更新价格历史
            self._price_history[stock_code] = prices

            return (ma5, ma10, ma20, ma30)

        except Exception as e:
            print(f"⚠️ {stock_code} MA计算异常: {e}")
            return None

    def _filter_data_before_time(self, df: pd.DataFrame, end_time: datetime) -> pd.DataFrame:
        """
        过滤掉指定时间之后的数据（回测模式使用）

        Args:
            df: 原始数据DataFrame
            end_time: 结束时间

        Returns:
            过滤后的DataFrame
        """
        try:
            if df.empty:
                return df

            # 确保时间列存在
            if '__time__' not in df.columns:
                return df

            # 过滤掉结束时间之后的数据
            filtered_df = df[df['__time__'] <= end_time]
            return filtered_df

        except Exception as e:
            print(f"⚠️ 数据过滤异常: {e}")
            return df

    def get_latest_ma(self, stock_code: str, end_time: Optional[datetime] = None) -> Optional[Tuple[float, float, float]]:
        """
        获取指定股票的最新MA值（上一分钟结束时的MA5、MA10、MA20）

        Args:
            stock_code: 股票代码
            end_time: 结束时间（回测模式使用，实时模式为None）

        Returns:
            (MA5, MA10, MA20)的元组，如果无法计算则返回None
        """
        try:
            # 确定当前日期
            if end_time is not None:
                # 回测模式：使用指定的结束时间
                today = end_time.strftime("%Y%m%d")
                current_time = end_time
            else:
                # 实时模式：使用当前时间
                today = datetime.now().strftime("%Y%m%d")
                current_time = datetime.now()

            # 检查缓存是否有效
            if self._is_cache_valid(stock_code, today):
                # 从缓存的价格历史计算MA
                prices = self._price_history.get(stock_code, [])
                if len(prices) >= max(self.ma_periods):
                    ma5 = sum(prices[-5:]) / 5 if len(prices) >= 5 else None
                    ma10 = sum(prices[-10:]) / 10 if len(prices) >= 10 else None
                    ma20 = sum(prices[-20:]) / 20 if len(prices) >= 20 else None
                    ma30 = sum(prices[-30:]) / 30 if len(prices) >= 30 else None
                    return (ma5, ma10, ma20, ma30)
                return None

            # 缓存无效，需要重新下载和计算
            print(f"🔄 {stock_code} 开始下载当日分钟数据...")

            # 下载分钟数据
            if not self._download_minute_data(stock_code, today):
                return None

            # 获取分钟数据
            df = self._get_minute_data(stock_code, today)
            if df is None:
                return None

            # 筛选交易时段内的数据（传入end_time参数）
            df = self._filter_trading_session_data(df, end_time)
            if df.empty:
                return None

            # 计算MA
            ma_result = self._calculate_ma_from_data(stock_code, df)

            # 更新缓存
            if ma_result is not None:
                self._cache_date[stock_code] = today
                self._cache_time[stock_code] = time.time()
                self._cache_minute[stock_code] = current_time.strftime("%Y%m%d%H%M")
                ##print(f"✅ {stock_code} MA计算完成: MA5={ma_result[0]:.2f}, MA10={ma_result[1]:.2f}, MA20={ma_result[2]:.2f}")
            else:
                ##print(f"⚠️ {stock_code} MA计算失败")
                pass

            return ma_result

        except Exception as e:
            print(f"❌ {stock_code} 获取MA异常: {e}")
            return None

    def get_ma_with_preview(self, stock_code: str, current_price: Optional[float] = None) -> Dict[str, Optional[Tuple[float, float, float]]]:
        """
        获取MA值，包括确认值和预览值

        Args:
            stock_code: 股票代码
            current_price: 当前价格（用于预览MA）

        Returns:
            包含确认MA和预览MA的字典
        """
        # 获取确认MA
        confirmed_ma = self.get_latest_ma(stock_code)

        # 计算预览MA
        preview_ma = None
        if current_price is not None and confirmed_ma is not None:
            preview_ma = self._calculate_preview_ma(stock_code, current_price)

        return {
            'confirmed': confirmed_ma,
            'preview': preview_ma
        }

    def _calculate_preview_ma(self, stock_code: str, current_price: float) -> Optional[Tuple[float, float, float]]:
        """计算预览MA（基于当前价格）"""
        try:
            prices = self._price_history.get(stock_code, [])
            if len(prices) < max(self.ma_periods) - 1:
                return None

            # 添加当前价格到价格列表
            preview_prices = prices + [current_price]

            # 计算预览MA
            ma5 = sum(preview_prices[-5:]) / 5 if len(preview_prices) >= 5 else None
            ma10 = sum(preview_prices[-10:]) / 10 if len(preview_prices) >= 10 else None
            ma20 = sum(preview_prices[-20:]) / 20 if len(preview_prices) >= 20 else None

            return (ma5, ma10, ma20)

        except Exception:
            return None

    def force_refresh(self, stock_code: str) -> Optional[Tuple[float, float, float]]:
        """强制刷新指定股票的MA数据"""
        self.reset(stock_code)
        return self.get_latest_ma(stock_code)

    def get_all_stock_ma(self, stock_codes: list) -> Dict[str, Optional[Tuple[float, float, float]]]:
        """批量获取多个股票的MA值"""
        results = {}
        for code in stock_codes:
            results[code] = self.get_latest_ma(code)
        return results

    def get_historical_ma_data(self, stock_code: str, start_time: datetime, end_time: datetime) -> Optional[pd.DataFrame]:
        """
        获取指定时间范围内的历史MA数据
        
        Args:
            stock_code: 股票代码
            start_time: 开始时间
            end_time: 结束时间
            
        Returns:
            包含时间、MA5、MA10、MA20的DataFrame，如果失败返回None
        """
        try:
            # 获取时间范围内的分钟数据
            start_date = start_time.strftime("%Y%m%d")
            end_date = end_time.strftime("%Y%m%d")
            
            # 下载数据
            if not self.xtdata:
                print("⚠️ xtdata未初始化，无法获取历史数据")
                return None
                
            # 下载历史数据
            self.xtdata.download_history_data(
                stock_code=stock_code,
                period="1m",
                start_time=start_date,
                end_time=end_date
            )
            time.sleep(0.1)
            
            # 获取数据
            data = self.xtdata.get_local_data(
                stock_list=[stock_code],
                period='1m',
                start_time=start_date,
                end_time=end_date
            )
            
            df = data.get(stock_code) if data else None
            if df is None or df.empty:
                print(f"⚠️ {stock_code} 历史数据为空")
                return None
            
            # 处理时间列
            time_col = next((c for c in df.columns if 'time' in c.lower()), None)
            price_cols = ['close', 'lastPrice', 'price', 'last', 'current']
            price_col = next((c for c in price_cols if c in df.columns), None)
            
            if not time_col or not price_col:
                print(f"⚠️ {stock_code} 无法识别时间列或价格列")
                return None
            
            # 时间格式处理
            if str(df[time_col].dtype) in ('int64', 'float64'):
                df['__time__'] = pd.to_datetime(df[time_col], unit='ms') + pd.Timedelta(hours=8)
            else:
                try:
                    df['__time__'] = pd.to_datetime(df[time_col], format='%Y%m%d%H%M%S', errors='coerce')
                except Exception:
                    df['__time__'] = pd.to_datetime(df[time_col], errors='coerce')
            
            df = df[df['__time__'].notna()].sort_values('__time__')
            
            # 筛选交易时段
            mask = [((self.MORNING_START <= ts.time() <= self.MORNING_END) or
                     (self.AFTERNOON_START <= ts.time() <= self.AFTERNOON_END)) for ts in df['__time__']]
            df = df[mask] if any(mask) else df
            
            # 筛选时间范围
            df = df[(df['__time__'] >= start_time) & (df['__time__'] <= end_time)]
            
            if df.empty:
                print(f"⚠️ {stock_code} 筛选后数据为空")
                return None
            
            # 计算MA
            prices = df[price_col].dropna().tolist()
            if len(prices) < max(self.ma_periods):
                print(f"⚠️ {stock_code} 数据不足，需要至少{max(self.ma_periods)}个数据点")
                return None
            
            # 为每个时间点计算MA
            ma_data = []
            for i in range(len(prices)):
                if i + 1 >= max(self.ma_periods):  # 确保有足够数据计算MA
                    ma5 = sum(prices[max(0, i-4):i+1]) / min(5, i+1) if i >= 4 else None
                    ma10 = sum(prices[max(0, i-9):i+1]) / min(10, i+1) if i >= 9 else None
                    ma20 = sum(prices[max(0, i-19):i+1]) / min(20, i+1) if i >= 19 else None
                    ma30 = sum(prices[max(0, i-29):i+1]) / min(30, i+1) if i >= 29 else None
                    
                    ma_data.append({
                        'time': df.iloc[i]['__time__'],
                        'price': prices[i],
                        'ma5': ma5,
                        'ma10': ma10,
                        'ma20': ma20,
                        'ma30': ma30
                    })
            
            result_df = pd.DataFrame(ma_data)
            print(f"✅ {stock_code} 历史MA数据获取成功，共{len(result_df)}个数据点")
            return result_df
            
        except Exception as e:
            print(f"❌ {stock_code} 获取历史MA数据异常: {e}")
            return None

    def detect_golden_cross(self, stock_code: str, start_time: datetime, end_time: datetime) -> Optional[Dict]:
        """
        检测MA金叉信号（状态机逻辑）
        
        Args:
            stock_code: 股票代码
            start_time: 开始时间
            end_time: 结束时间
            
        Returns:
            金叉信息字典，包含金叉时间、价格、MA值等，如果没有金叉返回None
        """
        try:
            # 获取历史MA数据
            ma_df = self.get_historical_ma_data(stock_code, start_time, end_time)
            if ma_df is None or len(ma_df) < 2:
                print(f"⚠️ {stock_code} 历史数据不足，无法检测金叉")
                return None
            
            # 状态机逻辑：检测三重金叉和死叉
            golden_crosses = []
            is_golden_cross_active = False  # 当前是否处于金叉状态
            
            print(f"🔍 {stock_code} 开始检测三重金叉，共{len(ma_df)}个数据点")
            
            for i in range(1, len(ma_df)):
                prev_row = ma_df.iloc[i-1]
                curr_row = ma_df.iloc[i]
                
                # 检查是否有有效的MA值
                if (prev_row['ma5'] is not None and prev_row['ma10'] is not None and prev_row['ma20'] is not None and
                    curr_row['ma5'] is not None and curr_row['ma10'] is not None and curr_row['ma20'] is not None):
                    
                    # 调试信息：显示MA值变化
                    if i <= 5 or i >= len(ma_df) - 5:  # 只显示前5个和后5个数据点
                        print(f"🔍 {stock_code} 时间{curr_row['time'].strftime('%H:%M')}: "
                              f"MA5={curr_row['ma5']:.6f}, MA10={curr_row['ma10']:.6f}, MA20={curr_row['ma20']:.6f}")
                        print(f"🔍 {stock_code} 前一时间: "
                              f"MA5={prev_row['ma5']:.6f}, MA10={prev_row['ma10']:.6f}, MA20={prev_row['ma20']:.6f}")
                        
                        # 显示MA差值
                        ma5_diff = curr_row['ma5'] - prev_row['ma5']
                        ma10_diff = curr_row['ma10'] - prev_row['ma10']
                        ma20_diff = curr_row['ma20'] - prev_row['ma20']
                        print(f"🔍 {stock_code} MA变化: "
                              f"MA5变化={ma5_diff:.6f}, MA10变化={ma10_diff:.6f}, MA20变化={ma20_diff:.6f}")
                    
                    # 三重金叉条件：
                    # 1. MA5从下方穿越MA10
                    # 2. MA5 > MA10 > MA20 > MA30 (向上排列)
                    ma5_cross_ma10 = (prev_row['ma5'] <= prev_row['ma10'] and curr_row['ma5'] > curr_row['ma10'])
                    ma_upward_alignment = (curr_row['ma5'] > curr_row['ma10'] > curr_row['ma20'] > curr_row['ma30'])
                    
                    if not is_golden_cross_active and ma5_cross_ma10 and ma_upward_alignment:
                        # 触发三重金叉
                        is_golden_cross_active = True
                        golden_cross = {
                            'time': curr_row['time'],
                            'price': curr_row['price'],
                            'ma5': curr_row['ma5'],
                            'ma10': curr_row['ma10'],
                            'ma20': curr_row['ma20'],
                            'cross_strength': curr_row['ma5'] - curr_row['ma10'],  # MA5与MA10的差值
                            'ma20_distance': curr_row['ma20'] - curr_row['ma5'],  # MA20与MA5的距离
                            'alignment_strength': (curr_row['ma5'] - curr_row['ma10']) + (curr_row['ma10'] - curr_row['ma20'])  # 排列强度
                        }
                        golden_crosses.append(golden_cross)
                        print(f"✅ {stock_code} 触发三重金叉: {curr_row['time'].strftime('%H:%M:%S')}")
                        print(f"   MA5={curr_row['ma5']:.6f} > MA10={curr_row['ma10']:.6f} > MA20={curr_row['ma20']:.6f}")
                        print(f"   前一时间: MA5={prev_row['ma5']:.6f}, MA10={prev_row['ma10']:.6f}, MA20={prev_row['ma20']:.6f}")
                        print(f"   穿越确认: MA5从{prev_row['ma5']:.6f}穿越到{curr_row['ma5']:.6f}")
                        print(f"   排列确认: MA5-MA10={curr_row['ma5']-curr_row['ma10']:.6f}, MA10-MA20={curr_row['ma10']-curr_row['ma20']:.6f}")
                        
                    # 死叉条件：MA5 < MA10 或 MA10 < MA20 或 MA20 < MA30 (破坏向上排列)
                    elif is_golden_cross_active and (curr_row['ma5'] < curr_row['ma10'] or curr_row['ma10'] < curr_row['ma20'] or curr_row['ma20'] < curr_row['ma30']):
                        # 触发死叉，结束金叉状态
                        is_golden_cross_active = False
                        print(f"❌ {stock_code} 触发死叉: {curr_row['time'].strftime('%H:%M:%S')}")
                        if curr_row['ma5'] < curr_row['ma10']:
                            print(f"   原因: MA5({curr_row['ma5']:.3f}) < MA10({curr_row['ma10']:.3f})")
                        if curr_row['ma10'] < curr_row['ma20']:
                            print(f"   原因: MA10({curr_row['ma10']:.3f}) < MA20({curr_row['ma20']:.3f})")
            
            if golden_crosses:
                # 返回最新的金叉
                latest_cross = golden_crosses[-1]
                print(f"✅ {stock_code} 检测到三重金叉:")
                print(f"   时间: {latest_cross['time'].strftime('%Y-%m-%d %H:%M:%S')}")
                print(f"   价格: {latest_cross['price']:.6f}")
                print(f"   MA5: {latest_cross['ma5']:.6f}")
                print(f"   MA10: {latest_cross['ma10']:.6f}")
                print(f"   MA20: {latest_cross['ma20']:.6f}")
                print(f"   金叉强度: {latest_cross['cross_strength']:.6f}")
                print(f"   MA20距离: {latest_cross['ma20_distance']:.6f}")
                print(f"   排列强度: {latest_cross['alignment_strength']:.6f}")
                
                # 添加详细分析
                ma5_ma10_diff = latest_cross['ma5'] - latest_cross['ma10']
                ma10_ma20_diff = latest_cross['ma10'] - latest_cross['ma20']
                print(f"   详细分析:")
                print(f"     MA5-MA10差值: {ma5_ma10_diff:.6f}")
                print(f"     MA10-MA20差值: {ma10_ma20_diff:.6f}")
                print(f"     MA5/MA10比值: {latest_cross['ma5']/latest_cross['ma10']:.8f}")
                print(f"     MA10/MA20比值: {latest_cross['ma10']/latest_cross['ma20']:.8f}")
                return latest_cross
            else:
                print(f"ℹ️ {stock_code} 在指定时间范围内未检测到金叉")
                return None
                
        except Exception as e:
            print(f"❌ {stock_code} 金叉检测异常: {e}")
            return None

    def detect_death_cross(self, stock_code: str, start_time: datetime, end_time: datetime) -> Optional[Dict]:
        """
        检测MA死叉信号
        
        Args:
            stock_code: 股票代码
            start_time: 开始时间
            end_time: 结束时间
            
        Returns:
            死叉信息字典，包含死叉时间、价格、MA值等，如果没有死叉返回None
        """
        try:
            # 获取历史MA数据
            ma_df = self.get_historical_ma_data(stock_code, start_time, end_time)
            if ma_df is None or len(ma_df) < 2:
                print(f"⚠️ {stock_code} 历史数据不足，无法检测死叉")
                return None
            
            # 检测死叉
            death_crosses = []
            for i in range(1, len(ma_df)):
                prev_row = ma_df.iloc[i-1]
                curr_row = ma_df.iloc[i]
                
                # 检查是否有有效的MA值
                if (prev_row['ma5'] is not None and prev_row['ma10'] is not None and
                    curr_row['ma5'] is not None and curr_row['ma10'] is not None):
                    
                    # 死叉条件：MA5从上方穿越MA10
                    if (prev_row['ma5'] >= prev_row['ma10'] and 
                        curr_row['ma5'] < curr_row['ma10']):
                        
                        death_cross = {
                            'time': curr_row['time'],
                            'price': curr_row['price'],
                            'ma5': curr_row['ma5'],
                            'ma10': curr_row['ma10'],
                            'ma20': curr_row['ma20'],
                            'prev_ma5': prev_row['ma5'],
                            'prev_ma10': prev_row['ma10'],
                            'cross_strength': curr_row['ma10'] - curr_row['ma5']  # 死叉强度
                        }
                        death_crosses.append(death_cross)
            
            if death_crosses:
                # 返回最新的死叉
                latest_cross = death_crosses[-1]
                print(f"✅ {stock_code} 检测到死叉:")
                print(f"   时间: {latest_cross['time'].strftime('%Y-%m-%d %H:%M:%S')}")
                print(f"   价格: {latest_cross['price']:.3f}")
                print(f"   MA5: {latest_cross['ma5']:.3f}")
                print(f"   MA10: {latest_cross['ma10']:.3f}")
                print(f"   死叉强度: {latest_cross['cross_strength']:.3f}")
                return latest_cross
            else:
                print(f"ℹ️ {stock_code} 在指定时间范围内未检测到死叉")
                return None
                
        except Exception as e:
            print(f"❌ {stock_code} 死叉检测异常: {e}")
            return None

    def analyze_strength_trend_after_golden_cross(self, stock_code: str, start_time: datetime, end_time: datetime, minutes_after: int = 30) -> Optional[Dict]:
        """
        分析金叉后N分钟的强度趋势
        
        Args:
            stock_code: 股票代码
            start_time: 开始时间
            end_time: 结束时间
            minutes_after: 金叉后分析的分钟数，默认30分钟
            
        Returns:
            包含强度趋势分析的字典
        """
        try:
            # 获取历史MA数据
            ma_df = self.get_historical_ma_data(stock_code, start_time, end_time)
            if ma_df is None or len(ma_df) < 2:
                print(f"⚠️ {stock_code} 历史数据不足，无法分析强度趋势")
                return None
            
            # 状态机逻辑：检测三重金叉
            golden_crosses = []
            is_golden_cross_active = False
            
            for i in range(1, len(ma_df)):
                prev_row = ma_df.iloc[i-1]
                curr_row = ma_df.iloc[i]
                
                # 检查是否有有效的MA值
                if (prev_row['ma5'] is not None and prev_row['ma10'] is not None and prev_row['ma20'] is not None and prev_row['ma30'] is not None and
                    curr_row['ma5'] is not None and curr_row['ma10'] is not None and curr_row['ma20'] is not None and curr_row['ma30'] is not None):
                    
                    # 三重金叉条件
                    ma5_cross_ma10 = (prev_row['ma5'] <= prev_row['ma10'] and curr_row['ma5'] > curr_row['ma10'])
                    ma_upward_alignment = (curr_row['ma5'] > curr_row['ma10'] > curr_row['ma20'] > curr_row['ma30'])
                    
                    if not is_golden_cross_active and ma5_cross_ma10 and ma_upward_alignment:
                        # 触发三重金叉
                        is_golden_cross_active = True
                        golden_cross = {
                            'time': curr_row['time'],
                            'price': curr_row['price'],
                            'ma5': curr_row['ma5'],
                            'ma10': curr_row['ma10'],
                            'ma20': curr_row['ma20'],
                            'cross_strength': curr_row['ma5'] - curr_row['ma10'],
                            'ma20_distance': curr_row['ma20'] - curr_row['ma5'],
                            'alignment_strength': (curr_row['ma5'] - curr_row['ma10']) + (curr_row['ma10'] - curr_row['ma20']),
                            'index': i  # 记录在数据中的索引位置
                        }
                        golden_crosses.append(golden_cross)
                        
                    # 死叉条件
                    elif is_golden_cross_active and (curr_row['ma5'] < curr_row['ma10'] or curr_row['ma10'] < curr_row['ma20']):
                        is_golden_cross_active = False
            
            if not golden_crosses:
                print(f"ℹ️ {stock_code} 在指定时间范围内未检测到金叉")
                return None
            
            # 分析每个金叉后的强度趋势
            trend_analysis = []
            for cross in golden_crosses:
                cross_time = cross['time']
                cross_index = cross['index']
                
                # 计算金叉后的时间范围
                end_analysis_time = cross_time + pd.Timedelta(minutes=minutes_after)
                
                # 获取金叉后的数据
                after_cross_data = ma_df[
                    (ma_df['__time__'] > cross_time) & 
                    (ma_df['__time__'] <= end_analysis_time)
                ].copy()
                
                if len(after_cross_data) < 2:
                    print(f"⚠️ {stock_code} 金叉后{minutes_after}分钟内数据不足")
                    continue
                
                # 计算每个时间点的强度
                strength_data = []
                for _, row in after_cross_data.iterrows():
                    if (row['ma5'] is not None and row['ma10'] is not None and row['ma20'] is not None):
                        cross_strength = row['ma5'] - row['ma10']
                        alignment_strength = (row['ma5'] - row['ma10']) + (row['ma10'] - row['ma20'])
                        ma20_distance = row['ma20'] - row['ma5']
                        
                        strength_data.append({
                            'time': row['time'],
                            'price': row['price'],
                            'ma5': row['ma5'],
                            'ma10': row['ma10'],
                            'ma20': row['ma20'],
                            'cross_strength': cross_strength,
                            'alignment_strength': alignment_strength,
                            'ma20_distance': ma20_distance
                        })
                
                if len(strength_data) < 2:
                    continue
                
                # 分析强度趋势
                initial_cross_strength = cross['cross_strength']
                initial_alignment_strength = cross['alignment_strength']
                
                final_cross_strength = strength_data[-1]['cross_strength']
                final_alignment_strength = strength_data[-1]['alignment_strength']
                
                # 计算强度变化
                cross_strength_change = final_cross_strength - initial_cross_strength
                alignment_strength_change = final_alignment_strength - initial_alignment_strength
                
                # 计算趋势方向（正数表示增强，负数表示减弱）
                cross_strength_trend = "增强" if cross_strength_change > 0 else "减弱" if cross_strength_change < 0 else "持平"
                alignment_strength_trend = "增强" if alignment_strength_change > 0 else "减弱" if alignment_strength_change < 0 else "持平"
                
                # 计算最大和最小强度
                cross_strengths = [d['cross_strength'] for d in strength_data]
                alignment_strengths = [d['alignment_strength'] for d in strength_data]
                
                max_cross_strength = max(cross_strengths)
                min_cross_strength = min(cross_strengths)
                max_alignment_strength = max(alignment_strengths)
                min_alignment_strength = min(alignment_strengths)
                
                # 计算强度波动性
                cross_strength_volatility = max_cross_strength - min_cross_strength
                alignment_strength_volatility = max_alignment_strength - min_alignment_strength
                
                trend_info = {
                    'golden_cross_time': cross_time,
                    'golden_cross_price': cross['price'],
                    'analysis_duration_minutes': minutes_after,
                    'data_points': len(strength_data),
                    'initial_strengths': {
                        'cross_strength': initial_cross_strength,
                        'alignment_strength': initial_alignment_strength
                    },
                    'final_strengths': {
                        'cross_strength': final_cross_strength,
                        'alignment_strength': final_alignment_strength
                    },
                    'strength_changes': {
                        'cross_strength_change': cross_strength_change,
                        'alignment_strength_change': alignment_strength_change
                    },
                    'trends': {
                        'cross_strength_trend': cross_strength_trend,
                        'alignment_strength_trend': alignment_strength_trend
                    },
                    'strength_ranges': {
                        'cross_strength_max': max_cross_strength,
                        'cross_strength_min': min_cross_strength,
                        'alignment_strength_max': max_alignment_strength,
                        'alignment_strength_min': min_alignment_strength
                    },
                    'volatility': {
                        'cross_strength_volatility': cross_strength_volatility,
                        'alignment_strength_volatility': alignment_strength_volatility
                    },
                    'detailed_data': strength_data
                }
                
                trend_analysis.append(trend_info)
            
            result = {
                'stock_code': stock_code,
                'analysis_period': f"{start_time.strftime('%Y-%m-%d %H:%M')} - {end_time.strftime('%Y-%m-%d %H:%M')}",
                'minutes_after_golden_cross': minutes_after,
                'total_golden_crosses': len(golden_crosses),
                'trend_analysis': trend_analysis
            }
            
            return result
            
        except Exception as e:
            print(f"❌ {stock_code} 强度趋势分析异常: {e}")
            return None

    def get_all_cross_signals(self, stock_code: str, start_time: datetime, end_time: datetime) -> Dict:
        """
        获取指定时间范围内的所有金叉和死叉信号（状态机逻辑）
        
        Args:
            stock_code: 股票代码
            start_time: 开始时间
            end_time: 结束时间
            
        Returns:
            包含所有金叉和死叉信号的字典
        """
        try:
            # 获取历史MA数据
            ma_df = self.get_historical_ma_data(stock_code, start_time, end_time)
            if ma_df is None or len(ma_df) < 2:
                return {'golden_crosses': [], 'death_crosses': [], 'total_signals': 0}
            
            # 状态机逻辑：检测三重金叉和死叉
            golden_crosses = []
            death_crosses = []
            is_golden_cross_active = False  # 当前是否处于金叉状态
            
            for i in range(1, len(ma_df)):
                prev_row = ma_df.iloc[i-1]
                curr_row = ma_df.iloc[i]
                
                # 检查是否有有效的MA值
                if (prev_row['ma5'] is not None and prev_row['ma10'] is not None and prev_row['ma20'] is not None and prev_row['ma30'] is not None and
                    curr_row['ma5'] is not None and curr_row['ma10'] is not None and curr_row['ma20'] is not None and curr_row['ma30'] is not None):
                    
                    # 三重金叉条件：
                    # 1. MA5从下方穿越MA10
                    # 2. MA5 > MA10 > MA20 > MA30 (向上排列)
                    ma5_cross_ma10 = (prev_row['ma5'] <= prev_row['ma10'] and curr_row['ma5'] > curr_row['ma10'])
                    ma_upward_alignment = (curr_row['ma5'] > curr_row['ma10'] > curr_row['ma20'] > curr_row['ma30'])
                    
                    if not is_golden_cross_active and ma5_cross_ma10 and ma_upward_alignment:
                        # 触发三重金叉
                        is_golden_cross_active = True
                        golden_cross = {
                            'time': curr_row['time'],
                            'price': curr_row['price'],
                            'ma5': curr_row['ma5'],
                            'ma10': curr_row['ma10'],
                            'ma20': curr_row['ma20'],
                            'cross_strength': curr_row['ma5'] - curr_row['ma10'],
                            'ma20_distance': curr_row['ma20'] - curr_row['ma5'],
                            'alignment_strength': (curr_row['ma5'] - curr_row['ma10']) + (curr_row['ma10'] - curr_row['ma20'])
                        }
                        golden_crosses.append(golden_cross)
                        
                    # 死叉条件：MA5 < MA10 或 MA10 < MA20 或 MA20 < MA30 (破坏向上排列)
                    elif is_golden_cross_active and (curr_row['ma5'] < curr_row['ma10'] or curr_row['ma10'] < curr_row['ma20'] or curr_row['ma20'] < curr_row['ma30']):
                        # 触发死叉，结束金叉状态
                        is_golden_cross_active = False
                        death_cross = {
                            'time': curr_row['time'],
                            'price': curr_row['price'],
                            'ma5': curr_row['ma5'],
                            'ma10': curr_row['ma10'],
                            'ma20': curr_row['ma20'],
                            'cross_strength': curr_row['ma10'] - curr_row['ma5']
                        }
                        death_crosses.append(death_cross)
            
            result = {
                'golden_crosses': golden_crosses,
                'death_crosses': death_crosses,
                'total_signals': len(golden_crosses) + len(death_crosses)
            }
            
            print(f"✅ {stock_code} 信号统计:")
            print(f"   金叉数量: {len(golden_crosses)}")
            print(f"   死叉数量: {len(death_crosses)}")
            print(f"   总信号数: {result['total_signals']}")
            
            return result
            
        except Exception as e:
            print(f"❌ {stock_code} 获取交叉信号异常: {e}")
            return {'golden_crosses': [], 'death_crosses': [], 'total_signals': 0}


# 为了保持向后兼容，保留原有的类名
StandardMACalculator = IndependentMACalculator

# 更新导出列表
__all__ = ["IndependentMACalculator", "StandardMACalculator"]

# 使用示例
if __name__ == "__main__":
    # 定义股票代码
    stock_code = "159605.SZ"  # 可以修改为您需要的股票代码
    # 创建MA计算器
    ma_calc = IndependentMACalculator(xtdata=xtdata)
    
    # 获取当前时间
    current_time = datetime.now()
    print(f"当前时间: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 获取最新MA（实时模式）
    print(f"\n=== 实时模式 ===")
    ma_result = ma_calc.get_latest_ma(stock_code)
    if ma_result is not None:
        ma5, ma10, ma20, ma30 = ma_result
        print(f"股票 {stock_code} 的最新MA (实时):")
        print(f"  计算时间: {current_time.strftime('%Y-%m-%d %H:%M')} (上一分钟)")
        print(f"  MA5: {ma5:.3f}")
        print(f"  MA10: {ma10:.3f}")
        print(f"  MA20: {ma20:.3f}")
        print(f"  MA30: {ma30:.3f}")
    else:
        print(f"无法获取 {stock_code} 的MA值")
    
    # 测试指定时间（回测模式）
    print(f"\n=== 回测模式 ===")
    target_time = datetime(2025, 9, 16, 10, 47, 1)  # 10:30:01
    print(f"回测时间: {target_time.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"说明: 获取 {target_time.strftime('%H:%M')} 之前的数据来计算MA")
    
    # 重置缓存以确保获取新数据
    ma_calc.reset(stock_code)
    
    ma_result_backtest = ma_calc.get_latest_ma(stock_code, target_time)
    if ma_result_backtest is not None:
        ma5, ma10, ma20, ma30 = ma_result_backtest
        print(f"股票 {stock_code} 的MA (回测):")
        print(f"  计算时间: {target_time.strftime('%Y-%m-%d %H:%M')} (上一分钟)")
        print(f"  MA5: {ma5:.3f}")
        print(f"  MA10: {ma10:.3f}")
        print(f"  MA20: {ma20:.3f}")
        print(f"  MA30: {ma30:.3f}")
    else:
        print(f"无法获取 {stock_code} 的MA值 (回测)")
    
    # 金叉检测示例
    print(f"\n=== 金叉检测示例 ===")
    # 设置检测时间范围（例如：今天上午9:30到11:30）
    today = datetime.now().date()
    start_time = datetime.combine(today, datetime.strptime("09:30", "%H:%M").time())
    end_time = datetime.combine(today, datetime.strptime("14:50", "%H:%M").time())
    
    print(f"检测时间范围: {start_time.strftime('%Y-%m-%d %H:%M')} - {end_time.strftime('%Y-%m-%d %H:%M')}")
    
    # 检测金叉
    golden_cross = ma_calc.detect_golden_cross(stock_code, start_time, end_time)
    if golden_cross:
        print(f"✅ 发现金叉信号!")
        print(f"   金叉时间: {golden_cross['time'].strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"   金叉价格: {golden_cross['price']:.6f}")
        print(f"   MA5: {golden_cross['ma5']:.6f}")
        print(f"   MA10: {golden_cross['ma10']:.6f}")
        print(f"   MA20: {golden_cross['ma20']:.6f}")
        print(f"   金叉强度: {golden_cross['cross_strength']:.6f}")
        print(f"   MA20距离: {golden_cross['ma20_distance']:.6f}")
        print(f"   排列强度: {golden_cross['alignment_strength']:.6f}")
        
        # 添加详细分析
        ma5_ma10_diff = golden_cross['ma5'] - golden_cross['ma10']
        ma10_ma20_diff = golden_cross['ma10'] - golden_cross['ma20']
        print(f"   详细分析:")
        print(f"     MA5-MA10差值: {ma5_ma10_diff:.6f}")
        print(f"     MA10-MA20差值: {ma10_ma20_diff:.6f}")
        print(f"     MA5/MA10比值: {golden_cross['ma5']/golden_cross['ma10']:.8f}")
        print(f"     MA10/MA20比值: {golden_cross['ma10']/golden_cross['ma20']:.8f}")
    else:
        print(f"ℹ️ 在指定时间范围内未发现金叉信号")
    
    # 检测死叉
    death_cross = ma_calc.detect_death_cross(stock_code, start_time, end_time)
    if death_cross:
        print(f"✅ 发现死叉信号!")
        print(f"   死叉时间: {death_cross['time'].strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"   死叉价格: {death_cross['price']:.3f}")
        print(f"   MA5: {death_cross['ma5']:.3f}")
        print(f"   MA10: {death_cross['ma10']:.3f}")
        print(f"   死叉强度: {death_cross['cross_strength']:.3f}")
    else:
        print(f"ℹ️ 在指定时间范围内未发现死叉信号")
    
    # 强度趋势分析示例
    print(f"\n=== 金叉后强度趋势分析 ===")
    trend_analysis = ma_calc.analyze_strength_trend_after_golden_cross(stock_code, start_time, end_time, minutes_after=30)
    if trend_analysis and trend_analysis['trend_analysis']:
        print(f"✅ {stock_code} 强度趋势分析结果:")
        print(f"   分析期间: {trend_analysis['analysis_period']}")
        print(f"   金叉后分析时长: {trend_analysis['minutes_after_golden_cross']}分钟")
        print(f"   检测到金叉数量: {trend_analysis['total_golden_crosses']}")
        
        for i, analysis in enumerate(trend_analysis['trend_analysis'], 1):
            print(f"\n   金叉 #{i}:")
            print(f"     金叉时间: {analysis['golden_cross_time'].strftime('%H:%M:%S')}")
            print(f"     金叉价格: {analysis['golden_cross_price']:.6f}")
            print(f"     分析数据点: {analysis['data_points']}个")
            
            # 初始强度
            print(f"     初始强度:")
            print(f"       金叉强度: {analysis['initial_strengths']['cross_strength']:.6f}")
            print(f"       排列强度: {analysis['initial_strengths']['alignment_strength']:.6f}")
            
            # 最终强度
            print(f"     最终强度:")
            print(f"       金叉强度: {analysis['final_strengths']['cross_strength']:.6f}")
            print(f"       排列强度: {analysis['final_strengths']['alignment_strength']:.6f}")
            
            # 强度变化
            print(f"     强度变化:")
            print(f"       金叉强度变化: {analysis['strength_changes']['cross_strength_change']:.6f}")
            print(f"       排列强度变化: {analysis['strength_changes']['alignment_strength_change']:.6f}")
            
            # 趋势方向
            print(f"     趋势方向:")
            print(f"       金叉强度趋势: {analysis['trends']['cross_strength_trend']}")
            print(f"       排列强度趋势: {analysis['trends']['alignment_strength_trend']}")
            
            # 强度范围
            print(f"     强度范围:")
            print(f"       金叉强度: {analysis['strength_ranges']['cross_strength_min']:.6f} ~ {analysis['strength_ranges']['cross_strength_max']:.6f}")
            print(f"       排列强度: {analysis['strength_ranges']['alignment_strength_min']:.6f} ~ {analysis['strength_ranges']['alignment_strength_max']:.6f}")
            
            # 波动性
            print(f"     波动性:")
            print(f"       金叉强度波动: {analysis['volatility']['cross_strength_volatility']:.6f}")
            print(f"       排列强度波动: {analysis['volatility']['alignment_strength_volatility']:.6f}")
            
            # 详细数据（显示前5个和后5个数据点）
            if len(analysis['detailed_data']) > 10:
                print(f"     详细数据 (前5个和后5个):")
                for j, data in enumerate(analysis['detailed_data'][:5]):
                    print(f"       {j+1}. {data['time'].strftime('%H:%M')}: "
                          f"金叉强度={data['cross_strength']:.6f}, "
                          f"排列强度={data['alignment_strength']:.6f}")
                print(f"       ... (省略中间{len(analysis['detailed_data'])-10}个数据点) ...")
                for j, data in enumerate(analysis['detailed_data'][-5:], len(analysis['detailed_data'])-4):
                    print(f"       {j}. {data['time'].strftime('%H:%M')}: "
                          f"金叉强度={data['cross_strength']:.6f}, "
                          f"排列强度={data['alignment_strength']:.6f}")
            else:
                print(f"     详细数据:")
                for j, data in enumerate(analysis['detailed_data']):
                    print(f"       {j+1}. {data['time'].strftime('%H:%M')}: "
                          f"金叉强度={data['cross_strength']:.6f}, "
                          f"排列强度={data['alignment_strength']:.6f}")
    else:
        print(f"ℹ️ {stock_code} 未检测到金叉或强度趋势分析失败")
    
    # 获取所有交叉信号
    print(f"\n=== 所有交叉信号统计 ===")
    all_signals = ma_calc.get_all_cross_signals(stock_code, start_time, end_time)
    if all_signals['total_signals'] > 0:
        print(f"总信号数: {all_signals['total_signals']}")
        print(f"金叉数量: {len(all_signals['golden_crosses'])}")
        print(f"死叉数量: {len(all_signals['death_crosses'])}")
        
        # 显示所有金叉
        if all_signals['golden_crosses']:
            print(f"\n所有金叉信号:")
            for i, cross in enumerate(all_signals['golden_crosses'], 1):
                print(f"  {i}. 时间: {cross['time'].strftime('%H:%M:%S')}, "
                      f"价格: {cross['price']:.6f}, "
                      f"MA5: {cross['ma5']:.6f}, "
                      f"MA10: {cross['ma10']:.6f}, "
                      f"MA20: {cross['ma20']:.6f}")
                print(f"     强度: 金叉={cross['cross_strength']:.6f}, "
                      f"排列={cross['alignment_strength']:.6f}, "
                      f"MA20距离={cross['ma20_distance']:.6f}")
                
                # 分析金叉前5分钟强度趋势
                print(f"     金叉前5分钟强度分析:")
                try:
                    # 获取金叉前5分钟的数据
                    cross_time = cross['time']
                    start_analysis_time = cross_time - pd.Timedelta(minutes=5)
                    
                    # 获取历史MA数据用于分析
                    ma_df = ma_calc.get_historical_ma_data(stock_code, start_time, end_time)
                    if ma_df is not None:
                        # 获取金叉前5分钟的数据（包括金叉点）
                        # get_historical_ma_data返回的DataFrame使用'time'列名
                        before_cross_data = ma_df[
                            (ma_df['time'] >= start_analysis_time) & 
                            (ma_df['time'] <= cross_time)
                        ].copy()
                        
                        if len(before_cross_data) >= 2:
                            # 计算每个时间点的强度
                            strength_data = []
                            for _, row in before_cross_data.iterrows():
                                if (row['ma5'] is not None and row['ma10'] is not None and row['ma20'] is not None):
                                    cross_strength = row['ma5'] - row['ma10']
                                    alignment_strength = (row['ma5'] - row['ma10']) + (row['ma10'] - row['ma20'])
                                    
                                    strength_data.append({
                                        'time': row['time'],
                                        'cross_strength': cross_strength,
                                        'alignment_strength': alignment_strength
                                    })
                            
                            if len(strength_data) >= 2:
                                # 分析强度趋势（从5分钟前到金叉点）
                                initial_cross_strength = strength_data[0]['cross_strength']  # 5分钟前的强度
                                initial_alignment_strength = strength_data[0]['alignment_strength']
                                
                                final_cross_strength = strength_data[-1]['cross_strength']  # 金叉点的强度
                                final_alignment_strength = strength_data[-1]['alignment_strength']
                                
                                # 计算强度变化（从5分钟前到金叉点）
                                cross_strength_change = final_cross_strength - initial_cross_strength
                                alignment_strength_change = final_alignment_strength - initial_alignment_strength
                                
                                # 判断趋势
                                cross_trend = "增强" if cross_strength_change > 0 else "减弱" if cross_strength_change < 0 else "持平"
                                alignment_trend = "增强" if alignment_strength_change > 0 else "减弱" if alignment_strength_change < 0 else "持平"
                                
                                # 计算最大和最小强度
                                cross_strengths = [d['cross_strength'] for d in strength_data]
                                alignment_strengths = [d['alignment_strength'] for d in strength_data]
                                
                                max_cross_strength = max(cross_strengths)
                                min_cross_strength = min(cross_strengths)
                                max_alignment_strength = max(alignment_strengths)
                                min_alignment_strength = min(alignment_strengths)
                                
                                # 判断是否持续增大到金叉点
                                is_continuously_increasing = (cross_trend == "增强" and alignment_trend == "增强")
                                
                                print(f"       5分钟前强度: 金叉={initial_cross_strength:.6f}, 排列={initial_alignment_strength:.6f}")
                                print(f"       金叉点强度: 金叉={final_cross_strength:.6f}, 排列={final_alignment_strength:.6f}")
                                print(f"       强度变化: 金叉={cross_strength_change:.6f}, 排列={alignment_strength_change:.6f}")
                                print(f"       趋势方向: 金叉={cross_trend}, 排列={alignment_trend}")
                                print(f"       强度范围: 金叉[{min_cross_strength:.6f}~{max_cross_strength:.6f}], 排列[{min_alignment_strength:.6f}~{max_alignment_strength:.6f}]")
                                
                                if is_continuously_increasing:
                                    print(f"       ✅ 金叉前5分钟强度持续增大到金叉点！")
                                elif cross_trend == "减弱" or alignment_trend == "减弱":
                                    print(f"       ❌ 金叉前5分钟强度减弱")
                                else:
                                    print(f"       ➖ 金叉前5分钟强度基本持平")
                                
                                # 显示详细数据（前3个和后3个）
                                if len(strength_data) > 6:
                                    print(f"       详细数据 (前3个和后3个):")
                                    for j, data in enumerate(strength_data[:3]):
                                        print(f"         {j+1}. {data['time'].strftime('%H:%M')}: 金叉={data['cross_strength']:.6f}, 排列={data['alignment_strength']:.6f}")
                                    print(f"         ... (省略中间{len(strength_data)-6}个数据点) ...")
                                    for j, data in enumerate(strength_data[-3:], len(strength_data)-2):
                                        print(f"         {j}. {data['time'].strftime('%H:%M')}: 金叉={data['cross_strength']:.6f}, 排列={data['alignment_strength']:.6f}")
                                else:
                                    print(f"       详细数据:")
                                    for j, data in enumerate(strength_data):
                                        print(f"         {j+1}. {data['time'].strftime('%H:%M')}: 金叉={data['cross_strength']:.6f}, 排列={data['alignment_strength']:.6f}")
                            else:
                                print(f"       ⚠️ 金叉前5分钟内有效数据不足")
                        else:
                            print(f"       ⚠️ 金叉前5分钟内数据不足")
                    else:
                        print(f"       ⚠️ 无法获取历史数据进行分析")
                except Exception as e:
                    print(f"       ❌ 强度分析异常: {e}")
        
        # 显示所有死叉
        if all_signals['death_crosses']:
            print(f"\n所有死叉信号:")
            for i, cross in enumerate(all_signals['death_crosses'], 1):
                print(f"  {i}. 时间: {cross['time'].strftime('%H:%M:%S')}, "
                      f"价格: {cross['price']:.6f}, "
                      f"MA5: {cross['ma5']:.6f}, "
                      f"MA10: {cross['ma10']:.6f}, "
                      f"MA20: {cross['ma20']:.6f}")
                print(f"     强度: 死叉={cross['cross_strength']:.6f}")
    else:
        print(f"在指定时间范围内未发现任何交叉信号")
    
    # 显示价格历史信息
    if stock_code in ma_calc._price_history:
        prices = ma_calc._price_history[stock_code]
        print(f"\n=== 价格历史信息 ===")
        print(f"价格数据点数: {len(prices)}")
        if len(prices) >= 5:
            print(f"最近5个价格: {[f'{p:.3f}' for p in prices[-5:]]}")
        if len(prices) >= 10:
            print(f"最近10个价格: {[f'{p:.3f}' for p in prices[-10:]]}")
        if len(prices) >= 20:
            print(f"最近20个价格: {[f'{p:.3f}' for p in prices[-20:]]}")
    
    print(f"\n=== 使用说明 ===")
    print(f"1. 金叉检测: ma_calc.detect_golden_cross(stock_code, start_time, end_time)")
    print(f"2. 死叉检测: ma_calc.detect_death_cross(stock_code, start_time, end_time)")
    print(f"3. 所有信号: ma_calc.get_all_cross_signals(stock_code, start_time, end_time)")
    print(f"4. 强度趋势分析: ma_calc.analyze_strength_trend_after_golden_cross(stock_code, start_time, end_time, minutes_after=30)")
    print(f"5. 历史MA数据: ma_calc.get_historical_ma_data(stock_code, start_time, end_time)")
    print(f"6. 金叉条件: 三重金叉（状态机逻辑）")
    print(f"   - 金叉触发: MA5从下方穿越MA10 且 MA5 > MA10 > MA20 > MA30")
    print(f"   - 死叉触发: MA5 < MA10 或 MA10 < MA20 或 MA20 < MA30 (破坏向上排列)")
    print(f"   - 状态管理: 触发金叉后需等死叉完成才能再次触发金叉")
    print(f"7. 死叉条件: MA5从上方穿越MA10 (MA5 < MA10 且 前一个时间点 MA5 >= MA10)")
    print(f"8. 强度趋势分析功能:")
    print(f"   - 分析金叉后N分钟内强度变化趋势")
    print(f"   - 计算金叉强度和排列强度的变化")
    print(f"   - 提供强度范围、波动性等统计信息")
    print(f"   - 显示每个时间点的详细强度数据")
    print(f"9. 数据来源: xtdata分钟K线数据，交易时段: 09:30-11:30, 13:00-15:00")